package com.hdoit.ares.logical.insu.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.brokerage.model.CarBrokerageRecord;
import com.hdoit.ares.logical.brokerage.service.ICarBrokerageRecordService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.insu.dao.IZhonganCarDao;
import com.hdoit.ares.logical.insu.model.ZhonganCar;
import com.hdoit.ares.logical.insu.service.IZhonganCarService;
import com.hdoit.ares.logical.policy.service.IListPolicyService;
import com.hdoit.ares.logical.tp.model.ZhonganCallback;
import com.hdoit.ares.selfcommon.enums.acc.GoldenBeanType;
import com.hdoit.ares.selfcommon.enums.acti.TaskId;
import com.hdoit.ares.selfcommon.enums.brokerage.ConfirmState;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.log.dialect.log4j2.Log4j2LogFactory;

/**
 * @author caochengmeng
 * @email
 * @createtime 2018年01月16日 11:56:15
 * @comment
 */
@Component
public class ZhonganCarServiceImpl extends SuperService<ZhonganCar> implements IZhonganCarService {

	private IGoldenBeanDetailService goldenBeanDetailService;
	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}
	@Resource
	public void setGoldenBeanDetailService(IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}

	private ICarBrokerageRecordService carBrokerageRecordService;

	public ICarBrokerageRecordService getCarBrokerageRecordService() {
		return carBrokerageRecordService;
	}

	@Resource
	public void setCarBrokerageRecordService(ICarBrokerageRecordService carBrokerageRecordService) {
		this.carBrokerageRecordService = carBrokerageRecordService;
	}

	private IListPolicyService listPolicyService;

	public IListPolicyService getListPolicyService() {
		return listPolicyService;
	}

	@Resource
	public void setListPolicyService(IListPolicyService listPolicyService) {
		this.listPolicyService = listPolicyService;
	}
	
	private IZhonganCarDao zhonganCarDao;
	public IZhonganCarDao getZhonganCarDao() {
		return zhonganCarDao;
	}
	@Resource
	public void setZhonganCarDao(IZhonganCarDao zhonganCarDao) {
		this.zhonganCarDao = zhonganCarDao;
	}

	@Override
	public String zhonganCarCallback(ZhonganCallback zhonganCallback) throws RuntimeException {
		ZhonganCar zhonganCar = new ZhonganCar();
		zhonganCar.setId(CommonUtils.getKeyId());
		zhonganCar.setRequestDate(DateUtils.getCurrent());
		zhonganCar.setNotifyType(zhonganCallback.getNotifyType());

		String bizContent = zhonganCallback.getBizContent();
		Map<String, Object> bizContentMap = JSONUtil.parseObj(bizContent);
		zhonganCar.setUserId(MapUtils.getString(bizContentMap, "userId"));
		
		String insurePlace = MapUtils.getString(bizContentMap, "insurePlace");
		String policyHolderName = MapUtils.getString(bizContentMap, "policyHolderName");
		
		zhonganCar.setVehicleBrand(MapUtils.getString(bizContentMap, "vehicleBrand"));
		zhonganCar.setRecipienterName(MapUtils.getString(bizContentMap, "recipienterName"));
		zhonganCar.setRecipienterAddress(MapUtils.getString(bizContentMap, "recipienterAddress"));
		try {
			String insurePlaceUtf8 = new String(insurePlace.getBytes(),"utf-8");
			zhonganCar.setInsurePlace(insurePlaceUtf8);
			
			String policyHolderNameUtf8 = new String(policyHolderName.getBytes(),"utf-8");
			zhonganCar.setPolicyHolderName(policyHolderNameUtf8);
			
			
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		
		zhonganCar.setVehicleVIN(MapUtils.getString(bizContentMap, "vehicleVIN"));
		zhonganCar.setVehicleEngineNo(MapUtils.getString(bizContentMap, "vehicleEngineNo"));
		zhonganCar.setVehicleOwnerCertificateNo(MapUtils.getString(bizContentMap, "vehicleOwnerCertificateNo"));		
		zhonganCar.setPolicyHolderPhoneNo(MapUtils.getString(bizContentMap, "policyHolderPhoneNo"));
		zhonganCar.setVehiclePolicyOrderNo(MapUtils.getString(bizContentMap, "vehiclePolicyOrderNo"));
		zhonganCar.setIsNetToTelemarket(MapUtils.getString(bizContentMap, "isNetToTelemarket"));
		zhonganCar.setRecipienterPhone(MapUtils.getString(bizContentMap, "recipienterPhone"));
		zhonganCar.setTaxPreimum(MapUtils.getString(bizContentMap, "taxPreimum"));
		zhonganCar.setPaymentWay(MapUtils.getString(bizContentMap, "paymentWay"));

		String installmentNo = MapUtils.getString(bizContentMap, "installmentNo");
		System.err.println("installmentNo" + installmentNo);
		if (!StringUtils.isEmpty(installmentNo)) {
			zhonganCar.setInstallmentNo(installmentNo);
		}

		String notifyType = zhonganCallback.getNotifyType();
		System.err.println("notifyType" + notifyType);
		if (notifyType == "2") {
			zhonganCar.setEndorsementType(MapUtils.getString(bizContentMap, "endorsementType"));
			zhonganCar.setBusinessTpEndorsementNo(MapUtils.getString(bizContentMap, "businessTpEndorsementNo"));
			zhonganCar.setBusinessFee(MapUtils.getString(bizContentMap, "businessFee"));

			try {
				Date businessApplyTime = DateUtils.convertString2Date(MapUtils.getString(bizContentMap, "businessApplyTime"));
				zhonganCar.setBusinessApplyTime(businessApplyTime);
			} catch (ParseException e) {
				Log4j2LogFactory.get().error("businessApplyTime set  error");
				e.printStackTrace();
			}

			try {
				Date businessEffectiveDate = DateUtils.convertString2Date(MapUtils.getString(bizContentMap, "businessEffectiveDate"));
				zhonganCar.setBusinessEffectiveDate(businessEffectiveDate);
			} catch (ParseException e) {
				Log4j2LogFactory.get().error("businessApplyTime set  error");
				e.printStackTrace();
			}

			zhonganCar.setCompelTpEndorsementNo(MapUtils.getString(bizContentMap, "compelTpEndorsementNo"));
			zhonganCar.setCompelFee(MapUtils.getString(bizContentMap, "compelFee"));

			try {
				Date compelApplyTime = DateUtils.convertString2Date(MapUtils.getString(bizContentMap, "compelApplyTime"));
				zhonganCar.setCompelApplyTime(compelApplyTime);
			} catch (ParseException e) {
				Log4j2LogFactory.get().error("businessApplyTime set  error");
				e.printStackTrace();
			}

			try {
				Date compelEndorEffectiveDate = DateUtils.convertString2Date(MapUtils.getString(bizContentMap, "compelEndorEffectiveDate"));
				zhonganCar.setCompelEndorEffectiveDate(compelEndorEffectiveDate);
			} catch (ParseException e) {
				Log4j2LogFactory.get().error("businessApplyTime set  error");
				e.printStackTrace();
			}
		}

		String oldPolicyNo = zhonganCallback.getOldPolicyNo();
		System.err.println("oldPolicyNo" + oldPolicyNo);
		if (!StringUtils.isEmpty(oldPolicyNo)) {
			zhonganCar.setOldPolicyNo(oldPolicyNo);
		}

		zhonganCar.setPolicyNo(zhonganCallback.getPolicyNo());

		String sumInsured = zhonganCallback.getSumInsured();
		System.err.println("sumInsured" + sumInsured);
		if (!StringUtils.isEmpty(sumInsured)) {
			zhonganCar.setSumInsured(sumInsured);
		}
		zhonganCar.setPremium(zhonganCallback.getPremium());

		try {
			Date effectiveDate = DateUtils.convertString2Date(zhonganCallback.getEffectiveDate());
			zhonganCar.setEffectiveDate(effectiveDate);
		} catch (ParseException e) {
			Log4j2LogFactory.get().error("zhongancar expiryDate set error" + e);
			e.printStackTrace();
		}

		String expiryDate1 = zhonganCallback.getExpiryDate();
		try {
			Date expiryDate2 = DateUtils.convertString2Date(expiryDate1);
			Date expiryDate3 = DateUtils.addDay(1, expiryDate2);
			Calendar expiryDatecalendar = Calendar.getInstance();
			expiryDatecalendar.setTime(expiryDate3);
			Date date = expiryDatecalendar.getTime();
			System.err.println(date + "date");
			zhonganCar.setExpiryDate(date);
		} catch (ParseException e) {
			Log4j2LogFactory.get().error("zhongancar expiryDate set error" + e);
			e.printStackTrace();
		}

		zhonganCar.setProductName(zhonganCallback.getProductName());
		zhonganCar.setPromoteCode(zhonganCallback.getPromoteCode());
		zhonganCar.setPromoteName(zhonganCallback.getPromoteName());
		zhonganCar.setPromoteFee(zhonganCallback.getPromoteFee());
		zhonganCar.setVehicleType(zhonganCallback.getVehicleType());

		zhonganCar.setModelStatus(ModelStatus.add);
		if (!applyChange(zhonganCar)) {
			Log4j2LogFactory.get().error("zhonganCar applyChange error");
		}

		System.err.println("进入车险分润 =======");
		if ("1".equals(zhonganCar.getVehicleType())) {
			CarBrokerageRecord carBrokerageRecord = new CarBrokerageRecord();
			carBrokerageRecord.setId(CommonUtils.getKeyId());

			carBrokerageRecord.setRecordDate(DateUtils.getCurrent());

			// 设置犹豫期
			// 获取保单生效日期距离现在的时间
			System.err.println("get into  date !");
			try {
				Date now = DateUtils.getCurrent();
				Calendar nowCalendar = Calendar.getInstance();
				Calendar startDateCalendar = Calendar.getInstance();
				nowCalendar.setTime(now);
				// Date effectiveDate =
				// DateUtils.convertString2Date(zhonganCar.getEffectiveDate());
				Date effectiveDate = DateUtils.convertString2Date(zhonganCallback.getEffectiveDate());
				startDateCalendar.setTime(effectiveDate);
				Integer day = DateUtils.getDaysBetween(nowCalendar, startDateCalendar);
				if (day > 10) {
					carBrokerageRecord.setHeisitateDate(10);
				} else {
					carBrokerageRecord.setHeisitateDate(day);
				}
			} catch (ParseException e) {
				Log4j2LogFactory.get().error("HeisitateDate set error");
			}

			System.err.println("out off date!");
			carBrokerageRecord.setCustomerId(zhonganCar.getUserId());
			carBrokerageRecord.setCurrency("元");
			carBrokerageRecord.setCompanyName("众安平安");
			carBrokerageRecord.setCarNo(zhonganCar.getVehicleLicencePlateNo());
			carBrokerageRecord.setCarName(zhonganCar.getVehicleBrand());

			// 投保人姓名电话
			carBrokerageRecord.setApplicantName(zhonganCar.getPolicyHolderName());
			carBrokerageRecord.setApplicantPhone(zhonganCar.getPolicyHolderPhoneNo());

			// 商业险保单号，任务号
			carBrokerageRecord.setBizInsureInfoPolicyNo(zhonganCar.getPolicyNo());
			carBrokerageRecord.setTaskId(zhonganCar.getVehiclePolicyOrderNo());

			carBrokerageRecord.setConfirmState(ConfirmState.unConfirm);
			String bizInsureInfoPremium = zhonganCar.getPremium();
			if (!StringUtils.isEmpty(bizInsureInfoPremium)) {
				carBrokerageRecord.setBizInsureInfo(Double.valueOf(bizInsureInfoPremium));
			}
			carBrokerageRecord.setModelStatus(ModelStatus.add);
			if (!carBrokerageRecordService.applyChange(carBrokerageRecord)) {
				throw new RuntimeException("carBrokerageRecord save error");
			}
			if(!listPolicyService.setZhonganCarPolicy(zhonganCar)){
				throw new RuntimeException("zhonganCarPolicy set error");
			}


		} else if ("2".equals(zhonganCar.getVehicleType())) {
			CarBrokerageRecord carBrokerageRecord = new CarBrokerageRecord();
			carBrokerageRecord.setId(CommonUtils.getKeyId());

			carBrokerageRecord.setCustomerId(zhonganCar.getUserId());
			carBrokerageRecord.setCurrency("元");
			carBrokerageRecord.setCompanyName("众安平安");
			carBrokerageRecord.setCarNo(zhonganCar.getVehicleLicencePlateNo());
			carBrokerageRecord.setCarName(zhonganCar.getVehicleBrand());

			// 投保人姓名电话
			carBrokerageRecord.setApplicantName(zhonganCar.getPolicyHolderName());
			carBrokerageRecord.setApplicantPhone(zhonganCar.getPolicyHolderPhoneNo());

			carBrokerageRecord.setRecordDate(DateUtils.getCurrent());
			// 交强险保单号，任务号
			carBrokerageRecord.setEfcInsureInfoPolicyNo(zhonganCar.getPolicyNo());
			carBrokerageRecord.setTaskId(zhonganCar.getVehiclePolicyOrderNo());
			carBrokerageRecord.setEfcInsureInfo(Double.valueOf(zhonganCar.getPremium()));

			carBrokerageRecord.setModelStatus(ModelStatus.add);
			if (!carBrokerageRecordService.applyChange(carBrokerageRecord)) {
				throw new RuntimeException("carBrokerageRecord save error");
			}

		}
		return "zhonganBusiness set success";
	}
	
/*	private boolean updataGoldenBean(Customer refereeCustomer) {
		// 判断上级今日是否招募1名初创，如果有就发500金豆
		if (customerService.queryCountDayMaker(refereeCustomer.getId()) == 1) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.dayMaker, 500, GoldenBeanType.dayMaker, refereeCustomer.getId())){
				return true;
			}
		}

		// 判断上级本周是否招募到3位创客，如果有就发1000金豆
		if (customerService.queryCountWeekMaker(refereeCustomer.getId()) == 3) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.weekMaker, 1000, GoldenBeanType.weekMaker, refereeCustomer.getId())){
				return true;
			}
			
		}

		// 判断上级本月是否招募到10位创客，如果有就发2000金豆
		if (customerService.queryCountMonthMaker(refereeCustomer.getId()) == 10) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.monthMaker, 2000, GoldenBeanType.monthMaker, refereeCustomer.getId())){
				return true;
			}
		}
		return false;
	}*/
	

	@Override
	public List<ZhonganCar> queryAllCarInsu(String customerId) {
		return zhonganCarDao.queryAllCarInsu(customerId);
	}

	@Override
	public ZhonganCar queryModelByVehiclePolicyOrderNo(String vehiclePolicyOrderNo,String vehicleType) {
		return zhonganCarDao.queryModelByVehiclePolicyOrderNoAndVehicleType(vehiclePolicyOrderNo,vehicleType);
	}

	@Override
	public ZhonganCar queryModelByPolicyNo(String policyNo) {
		return zhonganCarDao.queryModelByPolicyNo(policyNo);
	}
}